//
//  MQHomeTableViewController.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/10.
//  Copyright © 2016年 itheima. All rights reserved.
//
import SVProgressHUD
import UIKit

class MQHomeTableViewController: MQVistorTableViewController {
    
//    private var statuses : [MQStatus]?
    
    private lazy var statusListViewModel:MQStatusListViewModel = MQStatusListViewModel()
    
    private let MQTableViewCellReuse = "MQTableViewCellReuse"
    
    override func viewDidLoad() {
        if userLogin == false{
            loginView.setupInfo()
        }else{
            setupUI()
            loadUserData()
        }
    }
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", title: nil, target: self, action: "back")
            setupTableView()
    }
    private func setupTableView(){
        tableView.registerClass(MQStatusCell.self, forCellReuseIdentifier: MQTableViewCellReuse)
        
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 300
        
        tableView.separatorStyle = .None
//        tableView.rowHeight = 500
        
        //上拉加载
        tableView.tableFooterView = pullView
        
        //系统自带下拉刷新
//        refreshControl = UIRefreshControl()
//        refreshControl?.addTarget(self, action: "loadUserData", forControlEvents: UIControlEvents.ValueChanged)
//        tableView.addSubview(refreshControl!)
        
        //自定义下拉刷新控件
        tableView.addSubview(mqRefreshControl)
        mqRefreshControl.addTarget(self, action: "loadUserData", forControlEvents: UIControlEvents.ValueChanged)
        
        
    }
    // MARK: - 懒加载控件
    private lazy var showPullDownTip:UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 14)
        label.frame.size.width = SCREENW
        label.frame.size.height = 35
        label.frame.origin.x = 0
//        label.frame.origin.y = 64
        label.textAlignment = .Center
        label.backgroundColor = UIColor.orangeColor()
        label.hidden = true
        return label
        
    }()
    
    private lazy var pullView:UIActivityIndicatorView = {
        let pullView = UIActivityIndicatorView()
        pullView.activityIndicatorViewStyle = .WhiteLarge
        pullView.color = UIColor.purpleColor()
//        pullView.startAnimating()
        pullView.sizeToFit()
        return pullView
    }()
    
    //下拉刷新控件
    private lazy var mqRefreshControl:MQRefreshControl = MQRefreshControl()
    
    @objc private func back(){
        printfLog("------back")
        let vc = MQTempViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    //获取用户数据
   @objc private func loadUserData(){
    
        statusListViewModel.loadUserData(pullView.isAnimating()) { (isSuccess, count) -> () in
                if isSuccess{
                    self.tableView.reloadData()
//                    printfLog(count)
                    if self.pullView.isAnimating() == false{
                        self.showDownTipWithLabel(count)
                    }
                    
                }else{
                    SVProgressHUD.showErrorWithStatus("error")
                }
                self.pullView.stopAnimating()
                //                self.refreshControl?.endRefreshing()
                self.mqRefreshControl.endRefreshing()
            }
        }
    
    private func showDownTipWithLabel(count:Int){
        
        if showPullDownTip.hidden == false{
            return
        }
        showPullDownTip.hidden = false

        if let navigationController = self.navigationController{
            navigationController.view.insertSubview(showPullDownTip, belowSubview: navigationController.navigationBar)
        }
        showPullDownTip.text = (count == 0) ? "没有新数据" : "加载\(count)条数据"
        
        //执行动画
        UIView.animateWithDuration(1, animations: { () -> Void in
                self.showPullDownTip.frame.origin.y = CGRectGetMaxY((self.navigationController?.navigationBar.frame)!)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    self.showPullDownTip.frame.origin.y -= self.showPullDownTip.frame.size.height
                }, completion: { (_) -> Void in
                        self.showPullDownTip.hidden = true
            })
        }
    }
}

// MARK: - tableView的数据源方法
extension MQHomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusListViewModel.statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(MQTableViewCellReuse, forIndexPath: indexPath) as! MQStatusCell
        
        //设置数据
        cell.statusViewModel = statusListViewModel.statuses![indexPath.row]
        tableView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//        printfLog("将要显示第\(indexPath.row)行")
        if indexPath.row == statusListViewModel.statuses!.count - 1 && pullView.isAnimating() == false{
            printfLog("刷新数据")
            pullView.startAnimating()
            loadUserData()
            
        }
    }
}

